package com.malljelly.study.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * springmvc的拦截器
 */
@Component
@Slf4j
public class BaseInterceptor  implements HandlerInterceptor {

    private boolean open = true;

    private long startTime=0;
    private String url = null;
    private String viewName = null;
    private Date date = null;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        startTime = System.currentTimeMillis();
        date = new Date();
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (modelAndView!=null){
            viewName = modelAndView.getViewName();
        }

    }

    /**
     * 不管请求方法是否发生异常都会走afterCompletion方法
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        if (!open){
            return;
        }

        url = request.getRequestURI();

        log.info("--------------------------action请求----------------------------");
        String str = "";
        if (handler!=null){
            str =  handler.toString().trim();
            //去掉修饰符和参数
            int index = str.indexOf(" ");
            if(index!=-1) str = str.substring(index,str.length()-1).trim();
            index = str.indexOf(" ");
            if(index!=-1) str = str.substring(index+1,str.length()-1).trim();
            index = str.indexOf("(");
            if(index!=-1) str = str.substring(0,index).trim();
        }
        log.info("url: "+ url);
        log.info("method: "+ request.getMethod());
        log.info("调用方法："+str);
        log.info("参数：");

        Map parameterMap = request.getParameterMap();
        for (Object key:parameterMap.keySet()){
            String name = (String) key;
            String value = request.getParameter(name);
            log.info(name + " : " + value);
        }

        if (viewName!=null) {
            log.info("viewName: " + viewName);
        }
        log.info("耗时："+(System.currentTimeMillis()-startTime)+"毫秒");

    }

}
